import 'package:flutter/material.dart';
import 'package:jfexpress_ui/render/graphic_canvas.dart';

import '../core/coordinate_system.dart';

class OscilloscopeCoordinateSystem extends StatelessWidget
    implements CoordinateSystem {
  const OscilloscopeCoordinateSystem({super.key});

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (context, constraints) {
        final size = constraints.biggest;
        return CustomPaint(
          size: size,
          painter: OscilloscopeCoordinateSystemPainter(),
        );
      },
    );
  }
}

class OscilloscopeCoordinateSystemPainter extends CustomPainter {
  final double _cellHeight = 36;
  final double _cellWidth = 72;

  @override
  void paint(Canvas canvas, Size size) {
    GraphicCanvas gc = GraphicCanvas(canvas);

    final borderPaint = Paint()
      ..color = Colors.red
      ..style = PaintingStyle.stroke
      ..strokeWidth = 4
      ..isAntiAlias = true
      ..strokeCap = StrokeCap.round;

    final centerPaint = Paint()
      ..color = Colors.red
      ..style = PaintingStyle.stroke
      ..strokeWidth = 1.2
      ..isAntiAlias = true
      ..strokeCap = StrokeCap.round;

    final paint = Paint()
      ..color = Colors.red
      ..style = PaintingStyle.stroke
      ..strokeWidth = 0.3
      ..isAntiAlias = true
      ..strokeCap = StrokeCap.round;

    final List<double> dashPattern = [20, 10];

    int colLength = (size.width / _cellWidth).toInt();
    int rowLength = (size.height / _cellHeight).toInt();

    if (colLength.isOdd) {
      colLength--;
    }
    if (rowLength.isOdd) {
      rowLength--;
    }

    double cellHeight = size.height / rowLength;
    double cellWidth = size.width / colLength;

    for (int i = 0; i <= colLength; i++) {
      double x = i * cellWidth;
      if (i == 0 || i == colLength) {
        gc.drawLine(borderPaint, x, 0, x, size.height);
      } else if (i == colLength ~/ 2) {
        gc.drawDashLine(centerPaint, x, 0, x, size.height, dashPattern);
      } else {
        gc.drawLine(paint, x, 0, x, size.height);
      }
    }

    for (int j = 0; j <= rowLength; j++) {
      double y = j * cellHeight;
      if (j == 0 || j == rowLength) {
        gc.drawLine(borderPaint, 0, y, size.width, y);
      }
      if (j == 0 || j == rowLength || j == rowLength ~/ 2) {
        gc.drawDashLine(centerPaint, 0, y, size.width, y, dashPattern);
      } else {
        gc.drawLine(paint, 0, y, size.width, y);
      }
    }
  }

  @override
  bool shouldRepaint(CustomPainter oldDelegate) {
    return false;
  }
}
